<template>
  <div class="comdiv">
    <div class="con">
      <!-- search -->
      <div class="filter-container">
        <el-row>
          <el-col :span="6">
            <div>
              <el-select v-model="listQuery.companyId" placeholder="公司" @change="companySearch" style="width: 100%">
                <el-option
                  v-for="item in selectCompany"
                  :key="item._id"
                  :label="item.companyName"
                  :value="item._id">
                </el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div>
              <el-select v-model="listQuery.roleId" placeholder="角色" @change="roleSearch" clearable style="width: 100%">
                <el-option
                  v-for="item in selectRole"
                  :key="item._id"
                  :label="item.roleName"
                  :value="item._id">
                </el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <el-input @keyup.enter.native="handleFilter" style="width: 100%;" class="filter-item" clearable
                      placeholder="用户名/手机号"
                      v-model="listQuery.searchText"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getList">搜索
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="success"
                       icon="el-icon-plus">添加
            </el-button>
          </el-col>
        </el-row>
      </div>
      <!--table-->
      <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
        <el-table-column align="center" label="序号">
          <template slot-scope="scope"><span>{{scope.row.px}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="用户名">
          <template slot-scope="scope"><span>{{scope.row.user.username}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="昵称">
          <template slot-scope="scope"><span>{{scope.row.user.nickname}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="手机">
          <template slot-scope="scope"><span>{{scope.row.user.mobile}}</span></template>
        </el-table-column>

        <el-table-column align="center" label="角色">
          <template slot-scope="scope"><span>{{scope.row.roleList|$_roleList}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="职位">
          <template slot-scope="scope"><span>{{scope.row.positionList|$_positionList}}</span></template>
        </el-table-column>

        <el-table-column align="center" label="公司">
          <template slot-scope="scope"><span>{{scope.row.user.company.companyName}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!--<el-button type="success" plain @click="handleUpdate(scope.row)" size="small">-->
            <el-button type="primary" plain @click="handleUpdate(scope.row)" size="small">
              详情
            </el-button>
            <!--<el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <!--add-->
      <el-dialog :title="dialogStatus=='create'?'添加用户':'编辑用户'" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
                 style='width: 450px; margin-left:50px;'>

          <el-form-item label="用户名" prop="username">
            <el-input v-model="temp.username"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="temp.nickname"></el-input>
          </el-form-item>
          <el-form-item v-if="dialogStatus=='create'" label="密码" prop="password" show-password>
            <el-input v-model="temp.password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="temp.mobile"></el-input>
          </el-form-item>


          <el-form-item label="公司" prop="companyId">
            <el-select v-model="temp.companyId" @change="companyChange" placeholder="请选择" width>
              <el-option
                v-for="item in selectCompany"
                :key="item._id"
                :label="item.companyName"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="职位" prop="positionList">
            <el-select v-model="temp.positionList" multiple placeholder="请选择">
              <el-option
                v-for="item in selectPosition"
                :key="item._id"
                :label="item.dpname"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="角色" prop="roleList">
            <el-select v-model="temp.roleList" multiple placeholder="请选择">
              <el-option
                v-for="item in selectRole"
                :key="item._id"
                :label="item.roleName"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="简介" prop="brief">
            <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.brief" type="textarea" placeholder="个人简介"/>
          </el-form-item>
      <!--        <el-form-item label="真名" prop="realName">
                <el-input v-model="temp.realName"></el-input>
              </el-form-item>
              <el-form-item label="身份证" prop="identityCard">
                <el-input v-model="temp.identityCard"></el-input>
              </el-form-item>
              <el-form-item label="头像地址" prop="headUrl">
                <el-input v-model="temp.headUrl"></el-input>
              </el-form-item>-->
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData" id="cfmbtm1">确定</el-button>
          <el-button v-else type="primary" @click="updateData" id="cfmbtm2">确定</el-button>
        </div>
      </el-dialog>
      <!--分页组件-->
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"
                  @pagination="getList"/>

    </div>
  </div>
</template>

<script>

  /* eslint-disable */
  import {
    fetchList,
    fetchGet,
    createOne,
    updateOneNoId,
    deleteOnePut,
    rolesAll,
    positionAll,
    companyAll
  } from '@/api/common'
  import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'
  import Pagination from '@/components/Pagination'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'userList',
    directives: {waves},
    components: {Pagination},
    inject: ['_company'],
    filters: {
      $_roleList: (value) => {
        return value.map((v) => {
          return v.roleName
        })
      },

      $_positionList: (value) => {
        return value.map((v) => {
          return v.positionName
        })
      }
    },
    data() {
      return {
        list: null,
        total: 0,
        px: null, //最大序号
        listLoading: true,
        listQuery: {
          page: 1,
          size: 10, //每页几条
          number: 0, //当前页为第1页,从0计算
          searchText: '',
          companyId: this._company._id,
          roleId: '',
          sort: 'id'
        },
        //弹出层
        dialogFormVisible: false,
        dialogStatus: '',
        selectCompany: [],
        selectPosition: [],
        selectRole: [],
        temp: {},   //保存添加,编辑后提交的信息
        rules: {
          username: [
            {required: true, message: '请输入登录名', trigger: 'blur'}
          ],
          nickname: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入电话', trigger: 'blur'}
          ],
          companyId: [
            {required: true, message: '请选择公司', trigger: 'change'},
          ],
          departmentId: [
            {required: true, message: '请选择部门', trigger: 'change'},
          ],
          positionList: [
            {required: true, message: '请选择职位', trigger: 'change'},
          ],
          roleList: [
            {required: true, message: '请选择角色', trigger: 'change'},
          ],
        }
      }
    },
    mounted() {
      if (!this._company)
        ERRS('未获取到用户公司信息!')
      this.getList();
      this.initInfo();
    },
    methods: {
      companySearch(val) {
        this.listQuery.companyId = val;
        this.getList()
      },
      roleSearch(val) {
        this.listQuery.roleId = val;
        this.getList()
      },
      getList() {
        this.total = 0;
        this.listLoading = true;
        fetchGet(`auth/auths/companies/${this.listQuery.companyId}/register/condition?page=${this.listQuery.page}&roleId=${this.listQuery.roleId}&searchText=${this.listQuery.searchText}&size=${this.listQuery.size}`).then(res => {
          if (res.code == 0) {
            let dat = res.data
            console.log(res);
            this.listQuery.size = dat.size > 0 ? dat.size : this.listQuery.size; //每页几条 //每页几条
            this.listQuery.page = dat.page > 0 ? dat.page : 1; //当前页为第1页
            this.total = dat.totalElements; //共多少页
            this.list = dat.content;
            let insIndex = this.listQuery.size * (this.listQuery.page - 1);
            this.list = this.list.map((v, index) => {
              this.$set(v, 'px', insIndex + index + 1);
              // this.$set(v, 'roles',insIndex+index+1);
              this.px = insIndex + index + 1; //最大序号
              return v
            });
            console.log(this.list)

            this.$nextTick()
          } else {
            $err(res.message)
          }
          this.listLoading = false
        })
      },
      //职位
      companyChange(id) {
        this.temp.positionList = []
        positionAll(id).then(res => {
          if (res.code == 0) {
            let dat = res.data.map((v) => {
              this.$set(v, 'dpname', v.department.departmentName + ' → ' + v.positionName);
              return v
            })
            console.log(dat);
            this.selectPosition = dat;
          } else {
            ERRS('部门Err: ' + res.message)
          }
        })
      },
      initInfo() {
        //公司
        companyAll().then(res => {
          if (res.code == 0) {
            this.selectCompany = res.data;
          } else {
            ERRS('公司Err: ' + res.message)
          }
        })
        //角色
        rolesAll().then(res => {
          if (res.code == 0) {
            this.selectRole = res.data;
          } else {
            ERRS('角色Err: ' + res.message)
          }
        })
      }
      ,
      handleCreate() {
        this.companyChange(this._company._id)
        this.temp = {
          companyId: this._company._id,
          username: "",
          nickname: "",
          password: "",
          mobile: "",
          headerUrl: "http://njchome.b0.upaiyun.com/hlsnzj/default_header.jpg",
          brief: "",  //
          roleList: [],
          positionList: [],
        }
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
      ,
      //添加提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            createOne(`auth/auths/companies/${1}/register`, this.temp).then(response => {
              this.getList();
              this.dialogFormVisible = false
              $suc('创建成功')
            })
          }
        })
      }
      ,
      //详情修改
      handleUpdate(row) {
        let u = row.user
        let r = row.roleList
        let p = row.positionList
        console.log(row)
        this.companyChange(u.company._id)
        this.temp = {
          userId: u._id,
          companyId: u.company._id,
          username: u.username,
          nickname: u.nickname,
          password: "111",
          mobile: u.mobile,
          headerUrl: u.headerUrl,
          brief: u.brief,
          roleList: r.map(v => v._id),
          positionList: p.map(v => v._id),
        }
        console.log(this.temp);
        // return;

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      }
      ,
      //修改提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm2');
            // delete tempData.createdTime;
            // this.temp.password = this.temp.password.replace(/(^\s*)|(\s*$)/g, "")
            // if (!this.temp.password)
            delete this.temp.password
            console.log(this.temp)
            updateOneNoId(`auth/auths/companies/${this.temp.companyId}/register/${this.temp.userId}`, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('修改成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },

/*      //删除
      handleDelete(row) {
        this.$msgbox({
          // title: '删除',
          message: '确定要删除吗?',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOnePut(`auth/companies/${row.department.company._id}/positions/freeze`, row._id).then(res => {
            if (res.code === 0) {
              this.getList();
              SUCS('删除成功!')
            } else {
              ERRS(res.message)
            }
            this.dialogFormVisible = false
          })
        });
      },*/
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  @import './comp/index.scss';
</style>

